// pages/addimage/index.js
function getRandomColor() {
  let rgb = [];
  for (let i = 0; i < 3; i++) {
    let color = (Math.floor(Math.random() * 256)).toString(16);
    color = color.length == 1 ? ('0' + color) : color;
    rgb.push(color)
  }
  return "#" + rgb.join("");
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    titletop: '上传视频',
    videosUrllist: [],
    sendTime: 1,
    delbtn: true,
    danmu: '',
    danmulist: [{
      text: "这是第一条弹幕",
      time: 1,
      color: "#f00"
    }, {
      text: "这是第二条弹幕",
      time: 2,
      color: "#0f0"
    }, {
      text: "这是第三条弹幕",
      time: 6,
      color: "#00f"
    }],
  },
  timeUpdate: function (e) {
    //实时播放进度 秒数
    var currentTime = parseInt(e.detail.currentTime)
    // console.log("视频播放到第" + currentTime + "秒")//查看正在播放时间，以秒为单位
    this.setData({
      sendTime: currentTime
    })
  },

  doUpload() {
    // console.log('上传');
    let that = this //this重新赋值
    let num = 1
    wx.chooseMedia({
      count: 9, //最大选中（上传）数量
      sizeType: ['original', 'compressed'],
      mediaType: ['image', 'video'], //图片还是视频
      sourceType: ['album', 'camera'], // album相册//camera相机
      maxDuration: 60, // 拍摄视频最长拍摄时间，单位秒。时间范围为 3s 至 60s 之间。不限制相册
      camera: 'back',
      success(res) {
        num = res.tempFiles.length
        for (let i = 0; i < res.tempFiles.length; i++) {
          let uniqueFileName = 'myupload/' + +new Date() + '-' + Math.random() + '.png';
          wx.cloud.uploadFile({
            cloudPath: 'myupload/' + +new Date() + '.MP4',
            filePath: res.tempFiles[i].tempFilePath,
            success(res) {
              console.log(res, '成功上传到文件夹');
              //上传成功后将图片路径存入数据库 uploadimage
              wx.cloud.callFunction({
                name: 'addvideos',
                data: {
                  videosUrl: res.fileID
                },
                success(res) {
                  console.log(res.result._id, '路径存到数据库了');
                  //存到数据库后  创建弹幕库
                  let danmuobj = {
                    danmulist: [],
                    vid: res.result._id
                  }
                  wx.cloud.callFunction({
                    name: 'addDanMu',
                    data: danmuobj,
                    success(resq) {
                      console.log(resq, '++++');
                    }
                  })
                  num--
                  if (num == 0) {
                    console.log('我应该是最后执行的');
                    that.getupimglist()
                  }
                }
              })
              //将上传的图片添加到当前数据后面
              // that.setData({
              //   videosUrl:this.data.videosUrllist.push(res.fileID)
              // })
            },
            fail(err) {
              console.log(err, "错误");
            }
          })

        }

      },
    })
  },
  delvideo(e) {
    console.log(e.target.dataset);
    wx.cloud.deleteFile({
        fileList: [e.target.dataset.fileid]
      })
      .then(res => {
        console.log(res, '删除成功');
      })
      .catch(err => {
        console.log(err, '删除失败');
      })


    wx.cloud.callFunction({
        name: 'delvideos',
        data: {
          id: e.target.dataset.id
        }
      })
      .then(res => {
        console.log(res, '数据库也删除成功啦');
        this.getupimglist()
      })
    wx.cloud.callFunction({
        name: 'delDanMu',
        data: {
          vid: e.target.dataset.id
        }
      })
      .then(res => {
        console.log(res, '弹幕也删除成功啦');
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  inputDanMu(e) {
    this.setData({
      danmu: e.detail.value
    })
  },
  sendDanMu(e) {
    let that=this
    //拿到播放进度
    console.log(this.data.sendTime);
    //拿到当前视频的id
    console.log(e.target.dataset.id);
    let danmu = {
      text: that.data.danmu,
      time: that.data.sendTime,
      color: getRandomColor()
    }
    wx.cloud.callFunction({
      name: 'updateDanMu',
      data: {
        vid: e.target.dataset.id,
        danmu: danmu
      },
      success(resq) {
        that.setData({
          danmu: ''
        })
        wx.showToast({
          title: '发送成功',
        })
        that.getupimglist()
      }
    })
  },
  toVideo(){
    wx.openChannelsUserProfile({
      finderUserName:'sphPkzqa4o8b9Es',
      success:function(res){
        console.log(res,'跳转成功');
      },
      fail: function(err) {
        console.error('打开用户资料失败', err)
      },
      complete: function() {
        console.log('接口调用完成')
      }
    })

  },
  toLogin() {
    wx.switchTab({
      url: '/pages/aboutme/index',
    })
  },
  //读取数据库的值 将路径赋值到data
  getupimglist() {
    let that = this
    let videoList = []
    let danmulist = []
    wx.showLoading({
      title: '加载中...',
    })
    wx.cloud.callFunction({
        name: 'getvideos',
      })
      .then(res => {
        // that.setData({
        //   videosUrllist: res.result.data
        // })
        videoList = res.result.data
        wx.cloud.callFunction({
            name: 'getDanMu',
          })
          .then(res => {
            wx.stopPullDownRefresh();
            wx.hideLoading() 
            danmulist = res.result.data
            videoList.forEach(item => {
              danmulist.forEach(v => {
                if (item._id == v.vid) {
                  item.danmulist = v.danmulist
                }
              })
            })
            that.setData({
              videosUrllist: videoList
            })
          })
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this
    wx.getStorage({
      key: 'userpaw',
      success(e) {
        that.setData({
          delbtn: false
        })
      },
      fail() {
        that.setData({
          delbtn: true
        })
      }
    })
    this.getupimglist()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getupimglist()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
// pages/effects/audioCust/index.js